<template>
  <div class="member-management">
    <div class="page-header">
      <h2>会员管理</h2>
      <el-button type="primary" @click="showAddDialog = true">添加会员</el-button>
    </div>

    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索会员姓名或手机号"
        style="width: 300px"
        clearable
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <el-table :data="filteredMembers" style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="phone" label="手机号" width="150" />
      <el-table-column prop="cardNumber" label="会员卡号" width="150" />
      <el-table-column prop="points" label="积分" width="100" />
      <el-table-column prop="totalConsumption" label="总消费" width="120">
        <template #default="scope">
          ¥{{ scope.row.totalConsumption.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="lastVisitTime" label="最后访问" width="180" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="editMember(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteMember(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑会员对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingMember ? '编辑会员' : '添加会员'"
      width="500px"
    >
      <el-form :model="memberForm" :rules="rules" ref="memberFormRef" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="memberForm.name" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="memberForm.phone" />
        </el-form-item>
        <el-form-item label="会员卡号" prop="cardNumber">
          <el-input v-model="memberForm.cardNumber" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="memberForm.email" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="saveMember">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

export default {
  name: 'MemberManagement',
  components: {
    Search
  },
  setup() {
    const loading = ref(false)
    const members = ref([])
    const filteredMembers = ref([])
    const searchQuery = ref('')
    const showAddDialog = ref(false)
    const editingMember = ref(null)
    const memberFormRef = ref()

    const memberForm = reactive({
      name: '',
      phone: '',
      cardNumber: '',
      email: ''
    })

    const rules = {
      name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
      phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
      cardNumber: [{ required: true, message: '请输入会员卡号', trigger: 'blur' }]
    }

    const loadMembers = async () => {
      loading.value = true
      try {
        const response = await fetch('/api/members')
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }
        let data = await response.json()
        
        // 安全地提取数组数据
        if (Array.isArray(data)) {
          members.value = data
        } else if (data && Array.isArray(data.content)) {
          members.value = data.content // 适用于分页数据
        } else if (data && Array.isArray(data.data)) {
            members.value = data.data
        } else if (data && Array.isArray(data.list)) {
            members.value = data.list
        } else {
          console.error("API did not return a valid array for members:", data)
          members.value = []
          ElMessage.error('获取到的会员数据格式不正确')
        }

        filteredMembers.value = members.value
      } catch (error) {
        console.error("Failed to load members:", error)
        ElMessage.error('加载会员数据失败，将使用模拟数据')
        // 使用模拟数据
        members.value = [
          {
            id: 1,
            name: '张三 (模拟)',
            phone: '13800138001',
            cardNumber: 'VIP001',
            points: 1000,
            totalConsumption: 5000.00,
            lastVisitTime: '2024-01-15 14:30:00'
          },
          {
            id: 2,
            name: '李四 (模拟)',
            phone: '13800138002',
            cardNumber: 'VIP002',
            points: 800,
            totalConsumption: 3200.00,
            lastVisitTime: '2024-01-14 16:20:00'
          }
        ]
        filteredMembers.value = members.value
      } finally {
        loading.value = false
      }
    }

    const handleSearch = () => {
      if (!searchQuery.value) {
        filteredMembers.value = members.value
      } else {
        filteredMembers.value = members.value.filter(member =>
          member.name.includes(searchQuery.value) ||
          member.phone.includes(searchQuery.value)
        )
      }
    }

    const editMember = (member) => {
      editingMember.value = member
      Object.assign(memberForm, member)
      showAddDialog.value = true
    }

    const saveMember = async () => {
      try {
        const url = editingMember.value ? `/api/members/${editingMember.value.id}` : '/api/members'
        const method = editingMember.value ? 'PUT' : 'POST'
        
        const response = await fetch(url, {
          method,
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(memberForm)
        })

        if (response.ok) {
          ElMessage.success(editingMember.value ? '会员更新成功' : '会员添加成功')
          showAddDialog.value = false
          resetForm()
          await loadMembers()
        } else {
            const errorData = await response.json().catch(() => ({}))
            ElMessage.error(`操作失败: ${errorData.message || '未知错误'}`)
        }
      } catch (error) {
        ElMessage.error('操作失败，发生网络错误')
        // 模拟成功操作
        // ElMessage.success(editingMember.value ? '会员更新成功' : '会员添加成功')
        // showAddDialog.value = false
        // loadMembers()
        // resetForm()
      }
    }

    const deleteMember = async (id) => {
      try {
        await ElMessageBox.confirm('确定要删除这个会员吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        const response = await fetch(`/api/members/${id}`, { method: 'DELETE' })
        if (response.ok) {
          ElMessage.success('删除成功')
          await loadMembers()
        } else {
            ElMessage.error('删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除操作失败')
          // 模拟成功删除
          // ElMessage.success('删除成功')
          // loadMembers()
        }
      }
    }

    const resetForm = () => {
      editingMember.value = null
      Object.assign(memberForm, {
        name: '',
        phone: '',
        cardNumber: '',
        email: ''
      })
    }

    onMounted(() => {
      loadMembers()
    })

    onUnmounted(() => {
      // 清理组件状态
      loading.value = false
      showAddDialog.value = false
      editingMember.value = null
    })

    return {
      loading,
      members,
      filteredMembers,
      searchQuery,
      showAddDialog,
      editingMember,
      memberForm,
      memberFormRef,
      rules,
      handleSearch,
      editMember,
      saveMember,
      deleteMember
    }
  }
}
</script>

<style scoped>
.member-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 